package com.yunchang.springboot.scheduled.mwsfinance;

import com.yunchang.springboot.base.BaseService;
import com.yunchang.springboot.mapper.mws.finances.MwsFinancesEventGroupMapper;
import com.yunchang.springboot.mapper.mwsutils.CwfzFinancialSubjectsMapper;
import com.yunchang.springboot.mapper.mwsutils.CwfzRateMapper;
import com.yunchang.springboot.models.mwsfinance.FPaymentRebate;
import com.yunchang.springboot.models.mwsfinance.MwsFinancesEventGroup;
import com.yunchang.springboot.utils.DateUtil;
import com.yunchang.springboot.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * payment回款记录
 */
@Component
@Configuration
@Service
@Slf4j
@EnableScheduling
public class FPaymentRebateScheduled extends BaseService {

    static final String FORM = "Payment";

    static final String TRANSACTION_TYPE = "rebate";

    static final String PROCESSING_STATUS = "Closed";

    static final String FUND_TRANSFER_STATUS = "Succeeded";

    static final String COUNTRY_CODE = "GB";

    static final String COUNTRY_CODE_UK = "UK";

    static String DOCUMENTS_ID = "HKD";


    /**
     * 获取exchange_rate
     */
    private CwfzRateMapper cwfzRateMapper;

    @Autowired
    public void setCwfzRateMapper(CwfzRateMapper cwfzRateMapper) {
        this.cwfzRateMapper = cwfzRateMapper;
    }

    /**
     * finance中的回款原始数据
     */
    private MwsFinancesEventGroupMapper mwsFinancesEventGroupMapper;

    @Autowired
    public void setMwsFinancesEventGroupMapper(MwsFinancesEventGroupMapper mwsFinancesEventGroupMapper) {
        this.mwsFinancesEventGroupMapper = mwsFinancesEventGroupMapper;
    }

    /**
     * 借贷关系
     */
    private CwfzFinancialSubjectsMapper cwfzFinancialSubjectsMapper;

    @Autowired
    public void setCwfzFinancialSubjectsMapper(CwfzFinancialSubjectsMapper cwfzFinancialSubjectsMapper) {
        this.cwfzFinancialSubjectsMapper = cwfzFinancialSubjectsMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public void getFPaymentRebate() {
        List<MwsFinancesEventGroup> mwsFinancesEventGroupList = mwsFinancesEventGroupMapper.selectByFinanceStatus(1, PROCESSING_STATUS, FUND_TRANSFER_STATUS);
        if (null != mwsFinancesEventGroupList && !mwsFinancesEventGroupList.isEmpty()) {
            List<Object> fPaymentRebateList = new ArrayList<>(mwsFinancesEventGroupList.size());
            for (MwsFinancesEventGroup mwsFinancesEventGroup : mwsFinancesEventGroupList) {
                FPaymentRebate fPaymentRebate = new FPaymentRebate();
                fPaymentRebate.setIsManaulAdjust(1);
                fPaymentRebate.setDocumentsId(DOCUMENTS_ID + UUIDUtil.getUUID());
                String sellerId = mwsFinancesEventGroup.getSellerId();
                fPaymentRebate.setSellerId(sellerId);
                String countryCode = mwsFinancesEventGroup.getCountryCode();
                if (StringUtils.isEmpty(countryCode)) {
                    fPaymentRebate.setIsManaulAdjust(2);
                } else {
                    if(countryCode.equals(COUNTRY_CODE)){
                        countryCode = COUNTRY_CODE_UK;
                    }
                    fPaymentRebate.setCountry(countryCode);
                }
                fPaymentRebate.setDate(mwsFinancesEventGroup.getFundTransferDate());
                Double originalAmount = mwsFinancesEventGroup.getOriginalTotalCurrencyAmount();
                fPaymentRebate.setOriginalAmount(originalAmount);
                String originalCurrency = mwsFinancesEventGroup.getOriginalTotalCurrencyCode();
                fPaymentRebate.setOriginalCurrency(originalCurrency);
                Double convertedTotalCurrencyAmount = mwsFinancesEventGroup.getConvertedTotalCurrencyAmount();
                fPaymentRebate.setConvertedTotalCurrencyAmount(convertedTotalCurrencyAmount);
                String convertedTotalCurrencyCode = mwsFinancesEventGroup.getConvertedTotalCurrencyCode();
                fPaymentRebate.setConvertedTotalCurrencyCode(convertedTotalCurrencyCode);
                log.info("convertedTotalCurrencyAmount:" + convertedTotalCurrencyAmount + "originalCurrency:" + originalCurrency + "convertedTotalCurrencyCode:" + convertedTotalCurrencyCode);
                Double rate = getRate(convertedTotalCurrencyAmount, originalCurrency, convertedTotalCurrencyCode);
                fPaymentRebate.setRate(rate);
                fPaymentRebate.setAmountStandardCurrency(getAmountStandardCurrency(convertedTotalCurrencyAmount, originalAmount, rate));
                fPaymentRebate.setDebitSubjectId(getDebitSubjectId(sellerId, countryCode));
                fPaymentRebate.setCreditSubjectId(getCreditSubjectId(sellerId, countryCode));
                fPaymentRebate.setCreateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                fPaymentRebate.setUpdateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                mwsFinancesEventGroup.setFinanceStatus(2);
                fPaymentRebateList.add(fPaymentRebate);
            }
            try {
                baseInsertList(fPaymentRebateList);
                mwsFinancesEventGroupMapper.updateMwsFinancesEventGroupList(mwsFinancesEventGroupList);
            } catch (Exception e) {
                log.error("插入数据是出现错误，payment回款记录" + e);
                throw new RuntimeException("插入数据是出现错误，payment回款记录");
            }
        } else {
            log.info("未查询到对应的payment回款记录数据列表，时间为" + DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
        }

    }

    /**
     * 获取rate
     *
     * @param originalCurrency
     * @return
     */
    public Double getRate(Double convertedTotalCurrencyAmount, String originalCurrency, String convertedTotalCurrencyCode) {
        if (null == convertedTotalCurrencyAmount) {
            return cwfzRateMapper.selectRateByOriginalCurrency(originalCurrency);
        } else {
            return cwfzRateMapper.selectRateByOriginalCurrency(convertedTotalCurrencyCode);
        }
    }

    /**
     * 获取amountStandardCurrency
     *
     * @param convertedTotalCurrencyAmount
     * @param originalAmount
     * @param rate
     * @return
     */
    public Double getAmountStandardCurrency(Double convertedTotalCurrencyAmount, Double originalAmount, Double rate) {
        if (null == convertedTotalCurrencyAmount) {
            return originalAmount * rate;
        } else {
            return convertedTotalCurrencyAmount * rate;
        }
    }

    /**
     * 获取借方科目
     *
     * @param sellerId
     * @param country
     * @return
     */
    public String getDebitSubjectId(String sellerId, String country) {
        if (!StringUtils.isEmpty(sellerId) && !StringUtils.isEmpty(country)) {
            return cwfzFinancialSubjectsMapper.selectDebitSubjectIdPositiveBySellerIdAndCountryAndFormAndTransactionType(sellerId, country, FORM, TRANSACTION_TYPE);
        } else {
            log.info("获取借方科目，sellerId或country为空，payment回款数据");
            return null;
        }
    }

    /**
     * 获取贷方科目
     *
     * @param sellerId
     * @param country
     * @return
     */
    public String getCreditSubjectId(String sellerId, String country) {
        if (!StringUtils.isEmpty(sellerId) && !StringUtils.isEmpty(country)) {
            return cwfzFinancialSubjectsMapper.selectCreditSubjectIdPositiveBySellerIdAndCountryAndFormAndTransactionType(sellerId, country, FORM, TRANSACTION_TYPE);
        } else {
            log.info("获取贷方科目，sellerId或country为空，payment回款数据");
            return null;
        }
    }

}
